var socket = io();
jQuery.noConflict();
var commentBoxWidth = {"long":"320px",
"short":"30px"};

var formStyle = {
    display: 'inline !important',
    WebkitTransition: 'all', // note the capital 'W' here
    msTransition: 'all'// 'ms' is the only lowercase vendor prefix
};

var Comment = React.createClass({
    render: function () {
        var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
        return (
            <div className="comment" >
                <div className="commentAuthor" >
                    <button>{this.props.author}</button></div>
                <div className="panel" dangerouslySetInnerHTML={{__html: rawMarkup}}/>
            </div>
        );
    }
});

var CommentBox = React.createClass({
    initLoadCommentsFromServer: function (msg) {


        this.setState({data: msg});
    },
    loadCommentsFromServer: function (msg) {

        var comments = this.state.data;
        comments.push(msg);
        this.setState({data: comments});

    },
    handleCommentSubmit: function (comment) {
        var comments = this.state.data;
        comments.push(comment);

        this.setState({data: comments}, function () {
            socket.emit('put message', comment);

        });
    },
    getInitialState: function () {
        return {data: []};
    },
    componentDidMount: function () {

        socket.emit('get message','comments');


        var self = this;
        socket.on('broadcast message', function (msg) {

            self.loadCommentsFromServer(msg);
            jQuery(".commentBox .commentList .comment:last-child .commentAuthor button").focus();

        });
        socket.on('get message', function (msg) {

            self.initLoadCommentsFromServer(msg);

        });

        jQuery(".commentBox #fold").click(function(){
            jQuery(".commentBox .commentList").toggle();
            jQuery(".commentBox #chatBox").toggle();

            jQuery(".commentBox .commentHeader").toggle();
            if (jQuery(".commentBox").css('width') == commentBoxWidth.long){
                jQuery(".commentBox").css('width',commentBoxWidth.short);
            }else {
                jQuery(".commentBox").css('width',commentBoxWidth.long);
            }
        });



    },
    render: function () {
        return (
            <div className="commentBox">
                <button id="fold">f</button>
                <div className="commentHeader"><div>Comments</div></div>

                <CommentList data={this.state.data}/>

                <CommentForm onCommentSubmit={this.handleCommentSubmit} />
            </div>
        );
    }
});

var CommentList = React.createClass({
    render: function () {
        var commentNodes = this.props.data.map(function (comment, index) {
            return (
                // `key` is a React-specific concept and is not mandatory for the
                // purpose of this tutorial. if you're curious, see more here:
                // http://facebook.github.io/react/docs/multiple-components.html#dynamic-children
                <Comment author={comment.author} key={index}>
                    {comment.text}
                </Comment>
            );
        });
        return (
            <div className="commentList">
                {commentNodes}
            </div>
        );
    }
});

var CommentForm = React.createClass({
    handleSubmit: function (e) {
        e.preventDefault();
        var author = React.findDOMNode(this.refs.author).innerHTML.trim();
        var text = React.findDOMNode(this.refs.text).value.trim();
        if (!text || !author) {
            return;
        }

        this.props.onCommentSubmit({author: author, text: text});
        React.findDOMNode(this.refs.text).value = '';
        jQuery(".commentBox .commentList .comment:last-child .commentAuthor button").focus();
    },
    handleAuthor: function (e) {
        e.preventDefault();
        var author = React.findDOMNode(this.refs.inputauthor).value.trim();

        if (!author || author.length > 10 || author.toLowerCase() == "system") {
            return;
        }

        React.findDOMNode(this.refs.author).innerHTML = author;
        React.findDOMNode(this.refs.inputauthor).value = '';

    },
    handleSysInfo:function(msg){
      React.findDOMNode(this.refs.sysinfo).innerHTML = msg;
    },
    inputMsg:function(){
        socket.emit('broadcast info','{user} is typing');
    },
    render: function () {
        var self = this;
        socket.on('broadcast info',function(msg){
            self.handleSysInfo(msg);
        });

        jQuery('.commentForm textarea').bind('input',self.inputMsg() );

        return (
            <div id="chatBox">
                <form className="authorForm" onSubmit={this.handleAuthor} style={formStyle}>
                    <input type="text" placeholder="Pick a nickname" ref="inputauthor"/>
                    <button type="submit" >Save</button>
                    <div ref="author" placeholder="your nickname"></div>
                </form>
                <form className="commentForm" onSubmit={this.handleSubmit} style={formStyle}>
                    <textarea type="text" placeholder="Say something..." ref="text"/>
                    <div/>
                    <button type="submit">Send</button>
                </form>
                <div ref="sysinfo"> </div>
            </div>
        );
    }
});



React.render(
    <CommentBox url="comments.json" />,
    document.getElementById('stargazyCommentBox')
);
